package com.zx.kitchen.index.common.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.zx.kitchen.index.R;
import com.zx.kitchen.index.common.adapter.PrintDetailAdapter;
import com.zx.kitchen.index.common.entity.PrintOrderBean;
import com.zx.kitchen.index.common.mvp.presenter.PrintDetailPresenter;
import com.zx.kitchen.index.common.mvp.view.PrintDetailView;
import com.zx.kitchen.index.common.utils.ArithmeticUtils;
import com.zx.kitchen.index.common.utils.BluetoothUtil;
import com.zx.kitchen.index.common.utils.ESCUtil;
import com.zx.kitchen.index.common.utils.SystemProperties;
import com.zx.kitchen.index.common.utils.TimeUtil;
import com.zx.kitchen.index.common.view.MyListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/3/8.
 */

public class PrintDetailActivity extends Activity implements View.OnClickListener, PrintDetailView {
    private ImageView ivUserImg;
    private TextView tvUserMobilephone;
    private TextView tvUserTelephone;
    private TextView tvUserCashier;
    private TextView tvDeviceNum;
    private TextView tvPrintTime;
    private TextView tvCustomName;
    private MyListView listPrintOrder;
    private TextView tvTotalPrice;
    private TextView tvReceive;
    private TextView tvFavourable;
    private TextView tvFavourableNum;
    private TextView tvGetMoney;
    private TextView tvPrintAddress;
    private ImageView ivPrintQrcode;
    private ImageView toolbarLeft;
    private TextView toolbarTitle;
    private PrintDetailAdapter printDetailAdapter;
    private List<PrintOrderBean.OrderDetailBean> mList = new ArrayList<>();
    private PrintDetailPresenter printDetailPresenter;
    private String id = "";
    private PrintOrderBean printOrderBeans;
    private RadioGroup rgPrint;
    private int printType = 0;
    private String activity_print; //是否打印活动
    private boolean isPurchase = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print_detail);
        id = getIntent().getStringExtra("id");
        initView();
    }

    private void initView() {
        View view = findViewById(R.id.titleBar);
        toolbarLeft = (ImageView) view.findViewById(R.id.toolbar_leftLin);
        toolbarTitle = (TextView) view.findViewById(R.id.toolbar_title);
        ivUserImg = (ImageView) findViewById(R.id.iv_user_img);
        tvUserMobilephone = (TextView) findViewById(R.id.tv_user_mobilephone);
        tvUserTelephone = (TextView) findViewById(R.id.tv_user_telephone);
        tvUserCashier = (TextView) findViewById(R.id.tv_user_cashier);
        tvDeviceNum = (TextView) findViewById(R.id.tv_device_num);
        tvPrintTime = (TextView) findViewById(R.id.tv_print_time);
        tvCustomName = (TextView) findViewById(R.id.tv_custom_name);
        listPrintOrder = (MyListView) findViewById(R.id.list_print_order);
        tvTotalPrice = (TextView) findViewById(R.id.tv_total_price);
        tvReceive = (TextView) findViewById(R.id.tv_receive);
        tvFavourable = (TextView) findViewById(R.id.tv_favourable);
        tvFavourableNum = (TextView) findViewById(R.id.tv_favourable_num);
        tvGetMoney = (TextView) findViewById(R.id.tv_get_money);
        tvPrintAddress = (TextView) findViewById(R.id.tv_print_address);
        ivPrintQrcode = (ImageView) findViewById(R.id.iv_print_qrcode);
        rgPrint = (RadioGroup) findViewById(R.id.rg_print);

        toolbarTitle.setText("打印信息");
        toolbarTitle.setTextColor(getResources().getColor(R.color.blue));

        printDetailPresenter = new PrintDetailPresenter(getBaseContext(), this);
        printDetailPresenter.getFromNet(id, isPurchase);
        printDetailAdapter = new PrintDetailAdapter(getBaseContext(), mList);
        listPrintOrder.setAdapter(printDetailAdapter);

        findViewById(R.id.btn_print_order).setOnClickListener(this);
        toolbarLeft.setOnClickListener(this);
        toolbarTitle.setOnClickListener(this);
        rgPrint.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_custom:
                        printType = 0;
                        break;
                    case R.id.rb_business:
                        printType = 1;
                        break;
                }
            }
        });
    }

    private void showData(PrintOrderBean printOrderBean) {
        printOrderBeans = printOrderBean;
        /**
         * 1.设备的brand值；通常为'SUNMI'。
         2.设备的model；可以为'V1'，'M1-L'等。
         */
//        String brand = SystemProperties.get("ro.product.brand");
//        String model = SystemProperties.get("ro.product.model");

        if (Util.isOnMainThread()) {
            Glide.with(getApplicationContext()).load(printOrderBean.getSupplier().getLogo()).into(ivUserImg);
        }
        tvUserMobilephone.setText("联系方式 ：" + printOrderBean.getSupplier().getMobile());
        tvUserTelephone.setText("座机电话：" + printOrderBean.getSupplier().getCompanytel());
        tvUserCashier.setText("收银员 ：" + printOrderBean.getUser_name());
//        tvDeviceNum.setText("设备号：" + brand + "-" + model);
        tvPrintTime.setText("时间：" + printOrderBean.getOrder().getCreate_time());
        tvCustomName.setText("客户名称 ：" + printOrderBean.getOrder().getCustomer_name());
        tvTotalPrice.setText(printOrderBean.getOrder().getOrder_money() + "元");//总计
        tvReceive.setText(printOrderBean.getOrder().getOrder_money() + "元");//应收
        tvFavourable.setText(printOrderBean.getOrder().getDiscount_money() + "元");//优惠
        tvFavourableNum.setText(ArithmeticUtils.sub(printOrderBean.getOrder().getOrder_money(), printOrderBean.getOrder().getDiscount_money(), 2) + "元");
        tvGetMoney.setText(printOrderBean.getOrder().getReceive_money() + "元");//实收
        tvPrintAddress.setText("联系地址：" + printOrderBean.getSupplier().getCompanyaddress());
        Glide.with(this).load(printOrderBean.getSupplier().getQr_code()).into(ivPrintQrcode);
        activity_print = printOrderBean.getSupplier().getActivity_print();


        switch (printType) {
            case 0:
                rgPrint.check(R.id.rb_custom);
                break;
            case 1:
                rgPrint.check(R.id.rb_business);
                break;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_leftLin:
                finish();
                break;
            case R.id.btn_print_order:
                //调取打印
                printOrder(printOrderBeans);
                break;
            case R.id.toolbar_title:
                startActivity(new Intent(this, IndexActivity.class));
                break;
        }
    }

    private void printOrder(PrintOrderBean printOrderBean) {
        // 1: Get BluetoothAdapter
        BluetoothAdapter btAdapter = BluetoothUtil.getBTAdapter();
        if (btAdapter == null) {
            Toast.makeText(getBaseContext(), "Please Open Bluetooth!", Toast.LENGTH_LONG).show();
            return;
        }
        // 2: Get Sunmi's InnerPrinter BluetoothDevice
        BluetoothDevice device = BluetoothUtil.getDevice(btAdapter);
        if (device == null) {
            Toast.makeText(getBaseContext(), "Please Make Sure Bluetooth have InnterPrinter!",
                    Toast.LENGTH_LONG).show();
            return;
        }
        // 3: Generate a order data
        byte[] data = ESCUtil.generateMockData(printOrderBean);
        // 4: Using InnerPrinter print data
        BluetoothSocket socket = null;
        try {
            socket = BluetoothUtil.getSocket(device);
            BluetoothUtil.sendData(data, socket);
        } catch (IOException e) {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

    }

    @Override
    public void onSuccess(PrintOrderBean printOrderBean) {
        mList.addAll(printOrderBean.getOrder_detail());
        showData(printOrderBean);
    }


    @Override
    public void onFail(String str) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
